import { PaneModel } from "./PaneModel";
import { defineComponent } from "vue";
import { modelService } from "@/modules/model/service";
import { PropertyRow } from "../types";
import { PropertyGroupTableInfoResponse } from "@/modules/model/service/dto";

export interface GroupList {
  label: string;
  name: string;
  component: ReturnType<typeof defineComponent>;
  show: boolean;
  props?: any;
  groupId?: string;
  modelId?: string;
}

export interface PropertyGroupTableRow {
  icon: string;
  instanceId: string;
  name: string;
  cells: PropertyRow[];
  propertyKeyMap: Map<PropertyKey, PropertyRow>;
}
export interface PropertyGroupTableColumn {
  prop: string;
  label: string;
  name?: string;
  instancId?: string;
  key?: string;
  comp?: any;
  width?: number;
  minWidth?: number;
  height?: number;
  align?: string;
  icon?: string;
  type?: string;
}
export class GroupPaneModel extends PaneModel {
  loading = false;
  groupTableInfo?: PropertyGroupTableInfoResponse;

  columns: PropertyGroupTableColumn[] = [];
  initColumn() {
    this.columns = [];
  }
  async loadTable() {
    const groupId = this.tabsModel.data.activeTab;
    const projectId = this.tabsModel.projectId;
    const modelId = this.tabsModel.data.modelId;
    if (!projectId || !modelId || !groupId) return;
    if (!groupId) return;
    let res = await modelService.queryPropertyGroupInfo(projectId, modelId, groupId, []);
    if (res && res.rows && res.rows.length > 0) {
      res.rows.forEach((item: PropertyGroupTableRow) => {
        item.propertyKeyMap = new Map();

        item.cells.forEach((propetyRow: PropertyRow) => {
          item.propertyKeyMap.set(propetyRow.key, propetyRow);
        });
        modelService.formatModelProperties(projectId, item.instanceId, item.cells);
      });
    }

    this.groupTableInfo = res;

    const cols = res.rows[0]?.cells.map((propetyRow: PropertyRow) => {
      let columnItem: PropertyGroupTableColumn = {} as any;
      columnItem.prop = propetyRow.key;
      columnItem.label = propetyRow.name;
      columnItem.align = "left";
      columnItem.height = 26;
      columnItem.minWidth = 100;
      return columnItem;
    });
    this.columns = cols || [];
  }
  async loadDataWhenNotLoad() {
    if (!this.loaded) {
      await this.loadTable();
    }
  }

  async fresh() {
    this.loadTable();
  }

  async clear() {
    this.columns = [];
    this.loaded = false;
    this.groupTableInfo = undefined;
  }
}
